package cn.humaohua.study.yanmo_design_pattern.ch20.v2;

import org.apache.commons.lang3.StringUtils;

import java.util.*;

public class SecurityMgr {
    private static SecurityMgr instance = new SecurityMgr();

    private static Map<String, Collection<Flyweight>> map = new HashMap<>();

    public static SecurityMgr getInstance() {
        return instance;
    }

    private SecurityMgr() {
    }

    public boolean hasPermit(String user, String securityEntity, String permit) {
        if (StringUtils.isNotBlank(user)) {
            Collection<Flyweight> coll = queryByUser(user);
            if (coll != null && coll.size() > 0) {
                for (Flyweight flyweight : coll) {
                    if (flyweight.match(securityEntity, permit)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private Collection<Flyweight> queryByUser(String user) {
        Collection<Flyweight> coll = new ArrayList<>();
        for (String db : TestDB.db) {
            String[] arr = db.split(",");
            if (StringUtils.equals(user, arr[0])) {
                if (StringUtils.equals("2", arr[3])) {
                    UnsharedConcreteFlyweight unsharedConcreteFlyweight = new UnsharedConcreteFlyweight();
                    String[] auths = TestDB.map.get(arr[1]);
                    for (String auth : auths) {
                        Flyweight flyweight = FlyweightFactory.getInstance().getFlyweight(auth);
                        unsharedConcreteFlyweight.add(flyweight);
                    }
                    ((ArrayList<Flyweight>) coll).add(unsharedConcreteFlyweight);
                } else if (StringUtils.equals("1", arr[3])) {
                    coll.add(FlyweightFactory.getInstance().getFlyweight(arr[1] + "," + arr[2]));
                }

            }
        }
        return coll;
    }

    public void print() {
        Iterator<String> it = map.keySet().iterator();
        while (it.hasNext()) {
            String user = it.next();
            System.out.println("user=" + user);
            Collection<Flyweight> coll = map.get(user);
            for (Flyweight flyweight : coll) {
                System.out.println(flyweight);
            }
        }
    }
}
